package com.woniuxy.bookmall.controller;

import com.woniuxy.bookmall.entity.TUser;
import com.woniuxy.bookmall.exceptions.OrderSubmitFailException;
import com.woniuxy.bookmall.exceptions.UnderStockException;
import com.woniuxy.bookmall.service.OrderService;
import com.woniuxy.bookmall.vo.Cart;
import com.woniuxy.bookmall.vo.OrderVo;
import com.woniuxy.bookmall.vo.PayVo;
import com.woniuxy.bookmall.vo.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class OrderController {
    @Autowired
    OrderService orderService ;

    @RequestMapping("/order/submitOrder")
    @ResponseBody
    public ResponseResult submitOrder(Long addressId, Long[] bookId, HttpServletRequest request){
        try {
            TUser user = (TUser) request.getSession().getAttribute("userInfo");
            Long orderId = orderService.submitOrder(addressId, bookId, user);
            return new ResponseResult(200,"下单成功!",orderId);
        }catch (UnderStockException e) {
            e.printStackTrace();
            return new ResponseResult(201,e.getMessage());
        }catch (OrderSubmitFailException e){
            e.printStackTrace();
            return new ResponseResult(202,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(203,"系统异常，下单失败!");
        }
    }

    @RequestMapping("/order/toPay")
    public String toPay(Long orderId,HttpServletRequest request){
        //查询订单信息  根据订单ID 查询 订单对象
        OrderVo  order = orderService.findOrderById(orderId);
        //封装一个支付对象 PayVo
        PayVo payVo = new PayVo();
        payVo.setOrderId(order.getId());
        payVo.setOrderNum(order.getOrdernum());
        payVo.setAllPrice(order.getTotalprice());

        List<Cart> carts = order.getCarts();
        StringBuffer sb = new StringBuffer();
        for (Cart cart :carts) {
            sb.append(cart.getBookname()+",");
        }
        sb.substring(0,sb.length()-1);
        payVo.setBody(sb.toString());
        request.setAttribute("payVo",payVo);

        //在redis设置一个时间周期  15分钟

        return "toPay";
    }
}
